// mela onlie 购物车界面 订制
import { PureComponent } from "react";
import { Button, Modal, Picker, List, InputItem, DatePicker,NavBar, Icon } from "antd-mobile"
import { connect } from 'dva';
import { ActivityIndicator } from 'antd-mobile';
import { isNull, goToPage, handleImg,handleOSS } from '../../utils/helper';
import "./PlaceOrder.less"
import { Row, Col } from 'antd';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import "./place.css"
import enUs from 'antd-mobile/lib/date-picker/locale/en_US';
import MToast from "../../components/Util/MToast";
import moment from 'moment';
@connect(() => {
  return ({

  })
})
export default class PlaceOrder extends PureComponent {
  constructor(props) {
    super(props);
    this.timer = null;
    this.state = {
      loading: true,
      cartItems: [],
      order_type: -1,//收货方式 0 物流 1 自提
      cart_address: {
        // "recivier": "1",
        // "street": "2",
        // "city": "3",
        // "district": "4",
        // "country": "5",
        // "post_code": "6",
        // "concat": "7"
      },//地址对象
      have_address: false,//是否有地址
      date: "",//自提时间
      recivier: "",//联系人
      concat: "",//联系电话
      store_address: "",
      goods_id:"",
      quantity:"",
      delivery_price:0,//物流运费
      isOn:false,//Confirm order按钮的状态
      itemArr:[],
    }
  }
  componentWillMount() {
    let { dispatch, location } = this.props;
    dispatch({
      type: "global/setHeaderTitle",
      payload: {
        title: T("Fill in an order(填写订单)"),
        path: location.pathname + location.search,
      }
    });
    // window.location.reload();
    console.log("12",localStorage.getItem(MI_APP_CODE + "cart_address"))
    if(localStorage.getItem("order_type")==0){
      this.setState({
        order_type:0
      })
    }else if(localStorage.getItem("order_type")==1){
      this.setState({
        order_type:1
      })
    }
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "/qry/all?_c=app_user_address_list",
          params: [
          ],
          _c: "app_user_address_list"
        },
        callback: (result) => {
          let{addressItems}=this.state;
          let { data } = result;
          if(data.length==0){
            this.setState({
              have_address: false
            })
          }else{
            if(!isNull(localStorage.getItem(MI_APP_CODE + "cart_address"))){
              console.log("有存储的地址")
              this.setState({
                cart_address:JSON.parse(localStorage.getItem(MI_APP_CODE + "cart_address")),
                have_address: true,
              });
              localStorage.setItem("saveId",JSON.parse(localStorage.getItem(MI_APP_CODE + "cart_address")).id);
            }else{
              console.log("没有存储的地址")
              this.setState({
                have_address: true,
                cart_address:data[0]
              })
              localStorage.setItem("saveId",data[0].id);
            }

          }
          this.setState({
            loading: false

          })
        }
      }
    })
    // let cart_address = localStorage.getItem(MI_APP_CODE + "cart_address");
    // console.log(cart_address)
    // if(!isNull(localStorage.getItem(MI_APP_CODE + "cart_address"))){
    //   console.log("fgfgfg")
    //   this.setState({
    //     cart_address: JSON.parse(cart_address),
    //     have_address: true
    //   })
    // }else{
    //   console.log("sfdfdfdf")
    //   this.setState({
    //     have_address: false
    //   })
    // }

    let{goods_id,quantity,cartItems}=this.state;
    const query = location.search;
    console.log(query)
    if(isNull(query)){
      dispatch({
        type: "form/query",
        payload: {
          apiInfo: {
            url: "cart/list",
            params: [

            ]
          },
          data: {
            goods_id_array: 11,
          },
          callback: (result) => {
            let { data } = result;
            var arrJson=this.state.itemArr
            let cartItemsArr = JSON.parse(localStorage.getItem("cartItems"))
            console.log(cartItemsArr)
            cartItemsArr.map((item)=>{
              if(item.checked){
                arrJson.push(item)
              }

            })

            this.setState({
              loading: false,
              cartItems:arrJson,
              store_address: data.store_address
            })
            console.log(data.store_address)
          }
        }
      })
    }
    else{
      const arr = query.split('&') // ['?s=', 'f=7']
      const goods_id = arr[0].substr(4) // '1'
      const quantity = arr[1].substr(9) // '7'
      dispatch({
        type: "form/query",
        payload: {
          apiInfo: {
            url: "cart/list",
            params: [
              {
                "key":"goods_id",
                "value":goods_id
              },
              {
                "key":"quantity",
                "value":quantity
              }
            ]
          },
          callback: (result) => {
            let { data } = result;
            this.setState({
              loading: false,
              cartItems: data.cart_items,
              store_address: data.store_address
            })
          }
        }
      })
    }


    console.log(query)
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/row?_c=app_delivery_price_config",
          params: [

          ]
        },
        callback: (result) => {
          console.log(parseFloat(result.data.delivery_price));
          this.setState({
            delivery_price:parseFloat(result.data.delivery_price)
          })
        }
      }
    })
  }
  componentDidMount() {

  }
  renderList() {
    let { cartItems } = this.state;
    if (!cartItems || cartItems.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T("No products(暂无商品)")}
        </div>
      )
    }
    else {
      let contents = [];
      return (
        <div >
          <div style={{ padding: "5px 10px", fontSize: "16px", wordBreak: "break-all", lineHeight: 2 }} className="ellipsis1">
            {localStorage[MI_APP_CODE + "name"]}
          </div>
          <div>
            {
              cartItems.map((i, k) => {
                let { img_url, goods_name, price, quantity, item_id } = i;
               let img_url1= i.img_url.split(",")[0]
                return (
                  <Row key={k} style={{ padding: "8px 0px ", borderBottom: "1px solid #ddd",overflow:'hidden' }}>
                    {/*<div style={{float:'left',border:'1px solid #EEEDF2',width:'24px',heigth:'32px',textAlign:'center',lineHeight:'32px',color:'#595867',fontSize:'12px',fontWeight:'bold',marginTop:'10px'}}>{quantity}</div>*/}
                    {/*<div style={{float:'left',color:'#9C9BAB',fontSize:'13px',width:'24px',heigth:'32px',textAlign:'center',lineHeight:'32px',marginTop:'10px'}}>x</div>*/}
                    <Col style={{width:'56px',height:'56px'}} span={4}><img src={handleOSS(img_url1)} style={{width:'56px',height:'56px'}}/></Col>
                    <Col style={{color:'#595867',fontSize:'13px',margin:'5px 5% 5px 10px'}} span={14} className="ellipsis2">{goods_name}</Col>
                    <Col style={{color:'#F09600',fontSize:'15px',fontWeight:'bold',marginTop:'10px'}} span={4}>
                      <div style={{textAlign:'left'}}>€{price}</div>
                      <div style={{color:'#9C9BAB',fontSize:'12px',textAlign:'right'}}>x{quantity}</div>
                      </Col>
                  </Row>
                )
              })
            }
          </div>
        </div>
      )
    }
  }
  confirmOrder() {
    let { dispatch } = this.props;
    let { cart_address, cartItems, order_type, date, recivier, concat, leaveMessage,delivery_price,isOn } = this.state;
    this.confirmClick();
    if (order_type == -1) {
      MToast.fail(T("Please select way"), 1.5, null, false);
      return;
    }
    else if (order_type == 0) {//物流配送
      if (Object.keys(cart_address).length == 0) {
        MToast.fail(T("Enter shipping address"), 1.5, null, false);
        return;
      }
    }
    else {//自提
      if (isNull(recivier)) {
        MToast.fail(T("Per favore inserisci un nome.（请输入姓名）"), 3, null, false);
        return;
      }
      if (isNull(concat)) {
        MToast.fail(T("Per favore inserisci la Numero di telefono.（请输入联系电话）"), 3, null, false);
        return;
      }
      if (isNull(date)) {
        MToast.fail(T("Seleziona l'orario di arrivo.(请选择到店时间)"), 3, null, false);
        return;
      }
    }
    let pay_amount = 0;
    let freight_amount = order_type == 0 ? delivery_price : 0;
    cartItems.map(i => {
      pay_amount += i.price * i.quantity
    })
    this.setState({
      isOn:true
    })
    let total_amount = pay_amount + freight_amount;
      dispatch({
        type: "form/query",
        payload: {
          apiInfo: {
            url: "order/generateConfirmOrder",
            params: [

            ]
          },
          isEditCreate: true,
          data: {
            items: cartItems,
            order_type: order_type,
            total_amount: total_amount,
            pay_amount: pay_amount,
            freight_amount: freight_amount,

            street: order_type == 0 ? cart_address.street : "",
            city: order_type == 0 ? cart_address.city : "",
            country: order_type == 0 ? cart_address.country : "",
            district: order_type == 0 ? cart_address.district : "",
            post_code: order_type == 0 ? cart_address.post_code : "",

            recivier: order_type == 0 ? cart_address.recivier : recivier,
            concat: order_type == 0 ? cart_address.concat : concat,
            pick_up_time: order_type == 0 ? null : moment(date).valueOf(),

            note: leaveMessage
          },
          callback: (result) => {
            if(result.code ==10200){
              if(order_type == 0 ){
                console.log("dfdfdfdf")
                console.log(cart_address)
                dispatch({
                  type: "form/query",
                  payload: {
                    apiInfo: {
                      url: "/ent/update?_c=app_user_address",
                      params: [
                        {
                          key: "id",
                          value: cart_address.id
                        },
                        {
                          key: "recivier",
                          value: cart_address.recivier
                        },
                        {
                          key: "street",
                          value: cart_address.street
                        },
                        {
                          key: "city",
                          value: cart_address.city
                        },
                        {
                          key: "district",
                          value: cart_address.district
                        },
                        {
                          key: "country",
                          value: "IT"
                        },
                        {
                          key: "post_code",
                          value: cart_address.post_code
                        },
                        {
                          key: "concat",
                          value: cart_address.concat
                        }
                      ],
                      _c: "app_user_address"
                    },
                    callback: (result) => {
                      let { data } = result;

                    }
                  }
                })
              }else{
                console.log("自提")
              }
              MToast.info(T("Ordina con successo.（下单成功）",3, null, false));
              setTimeout(() => {
                if (browser.isInApp) {
                  Func.callHander(bridge, "openHomePage", {})
                }
                // else{
                //   this.props.history.replace("/");
                //   window.location.reload();
                // }
                goToPage({ dispatch, config: { url: "/shop_home" }, })
              }, 500);
            }else{
              MToast.info(result.msg);
              this.setState({
                isOn:false
              })
            }


          }
        }
      });


    // 确认下单 成功之后提示下单成功 然后返回首页
    // goToPage({ dispatch, config: { url: "/page?_c=mela_shop_home" }, })
  }
  // 填写地址页面返回时触发
  changeAddress = () => {
    let cart_address = localStorage.getItem(MI_APP_CODE + "cart_address");
    console.log("cart_address:" + cart_address);
    if (!isNull(cart_address)) {
      localStorage.removeItem(MI_APP_CODE + "cart_address");
      this.setState({
        cart_address: JSON.parse(cart_address),
        have_address: true
      })
    }
  }
  confirmClick=()=>{
    let { dispatch } = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          "url": "qry/exec?_c=opreation_log",
          "params": [
            {
              "key": "opreation_info",
              "value":"提交订单按钮"
            },
            {
              "key": "opreation_id",
              "value":"5"
            }
          ]
        },
        callback: (result) => {
          console.log(result)
        }
      }
    })
  }
  render() {
    let { dispatch } = this.props;
    let { loading, cartItems, order_type, have_address, cart_address, store_address,currentQuantity, currentItem_id,delivery_price,isOn } = this.state;
    if (loading) {
      return (
        <div className="normal">
          <ActivityIndicator toast text="正在加载" animating={true} />
        </div>
      )
    }
    let totalPrice = 0;
    let total = 0;
    cartItems.map(i => {
      totalPrice += i.price * i.quantity
    })
    console.log(totalPrice)
    if (order_type == 0) {
      total = totalPrice + delivery_price
    }
    else {
      total = totalPrice
    }
    let order_type_value = []
    if (isNull(order_type)) {
      order_type_value = []
    }
    else {
      order_type_value = [order_type * 1]
    }
    return (
      <div className="normal placeOrder" style={{ background: "#fff",paddingTop:'0px' }}>
        {/*<div><img  src="image/arrow_left.png" style={{width:"25px",height:"25px",position:'fixed',top:'9px',left:'15px',zIndex:'100'}} onClick={()=>goToPage({ dispatch, config: { url: "/way" }, isReplace: false })}/></div>*/}
        {/*<NavBar*/}
          {/*mode="dark"*/}
          {/*icon={<img src="image/arrow_left.png" style={{width:'25px',height:'25px'}}/>}*/}
          {/*onLeftClick={() => goToPage({ dispatch, config: { url: "/way" }, isReplace: false })}*/}
        {/*>Fill in an order(填写订单)</NavBar>*/}
        <div style={{padding:'0px 0px 12px'}}>
          <div style={{ fontSize: "14px" }}>
            {
              order_type==0 &&
              <div style={{ padding: "15px 10px 10px", background: "#fff",borderBottom:"3px dotted #dddddd" }} className="mrequired">
                <div style={{color:'#2E2D35',fontSize:'18px',fontWeight:'bold',marginBottom:'20px'}}>Address</div>
                {
                  have_address?
                    <div style={{overflow:'hidden'}}>
                      <div style={{float:'left',width:'32px',height:'32px',padding:'2px'}}>
                        <img src="image/way1.png" style={{width:'24px',height:'24px'}}/>
                      </div>

                      <div style={{margin:"0 20px",fontSize:'14px',float:'left',color:'#9C9BAB',fontWeight:'bold',width:'60%'}}>
                        <p style={{marginBottom:'5px'}}>{cart_address.country} {cart_address.district} {cart_address.city} {cart_address.street}</p>
                        <p style={{marginBottom:'5px'}}> {cart_address.recivier}{cart_address.concat}</p>
                        <p style={{marginBottom:'0px'}}>{cart_address.post_code}</p>
                      </div>
                      <div onClick={()=>{
                        if(browser.isInApp){
                          Func.registerHanderBridge("callbackEventBack",this.changeAddress)
                        }
                        goToPage({ dispatch, config: { url: "/addressList" }, isReplace: false })
                      }} style={{float:'left',color:'#F09600',fontSize:'14px',fontWeight:'bold',marginTop:'20px'}}>Change</div>
                    </div>
                    :
                    <div style={{border:'1px dashed #DDE3E9',width:'100%',height:'64px'}} onClick={() => {
                      if (browser.isInApp) {
                        Func.registerHanderBridge("callbackCloseWindow", this.changeAddress);
                      }
                      goToPage({ dispatch, config: { url: "/addAddress" }, isReplace: false })
                    }}>
                      <div style={{overflow:'hidden',margin:'16px auto 16px',width:'66%'}}>
                        <div style={{float:'left',width:'30px',padding:'2px',marginRight:'20px'}}> <img src="image/address.png" style={{width:'24px'}}/></div>
                        <div style={{float:'left'}}>
                          <div style={{color:'#9C9BAB',fontSize:'12px',fontWeight:'bold'}}>Aggiungi nuovo indirizzo</div>
                          <div style={{color:'#9C9BAB',fontSize:'12px',fontWeight:'bold'}}>填写收货地址</div>
                        </div>

                      </div>

                    </div>
                }
              </div>
            }
            {
              order_type == 1 && <div>
                <div style={{ padding: "17% 32px 16px",background: "#39AA98",borderBottom:'10px solid #F3F3F5' }} className="mrequired">
                  <div data-flex="main:center cross:center box:first">
                    <div style={{width:'34px',height:'34px'}}><img src="image/store.png" style={{width:"32px"}}/></div>
                    <div style={{margin:"0 10px",fontSize:'12px'}}>
                      <p style={{marginBottom:'5px',color:'#fff',fontWeight:'bold'}}>{store_address}</p>
                    </div>
                  </div>
                </div>
                <div style={{padding:'16px'}}>
                  <div style={{color:'#2E2D35',fontSize:'17px',fontWeight:'bold',marginBottom:'24px'}}>Info 请填写</div>
                  <div style={{border:'1px solid #EEEDF2',borderRadius:'5px',position:'relative',padding:'5px 0'}}>
                    <div style={{color:'#9C9BAB',fontSize:'11px',position:'absolute',top:'-19px',left:'23px',zIndex:'10',background:'#fff',padding:'8px'}}>Nome e cognome 姓名</div>
                    <InputItem
                      clear
                      className="required"
                      onChange={(e) => {
                        this.setState({
                          recivier: e
                        })
                      }}
                      placeholder="Nome e cognome(填写姓名)"
                    ></InputItem>
                  </div>
                  <div style={{border:'1px solid #EEEDF2',borderRadius:'5px',position:'relative',padding:'5px 0',margin:'24px 0'}}>
                    <div style={{color:'#9C9BAB',fontSize:'11px',position:'absolute',top:'-19px',left:'23px',zIndex:'10',background:'#fff',padding:'8px'}}>Numero di telefono 电话</div>
                    <InputItem
                      clear
                      className="required"
                      onChange={(e) => {
                        this.setState({
                          concat: e
                        })
                      }}
                      placeholder="Numero di telefono(联系电话)"
                    ></InputItem>
                  </div>
                  <div style={{border:'1px solid #EEEDF2',borderRadius:'5px',position:'relative',padding:'5px 0'}}>
                    <div style={{color:'#9C9BAB',fontSize:'11px',position:'absolute',top:'-19px',left:'23px',zIndex:'10',background:'#fff',padding:'8px'}}>Orario di arrivo 到店时间</div>
                    <DatePicker
                      locale={enUs}
                      mode="date"
                      className="required"
                      title={T("Orario di arrivo(到店时间)")}
                      extra={T("Select(请选择)")}
                      value={this.state.date}
                      onChange={date => this.setState({ date })}
                      okText={T("Ok")}
                      dismissText={T("Cancel")}>
                      <List.Item arrow="horizontal">{T("Orario di arrivo(到店时间)")}:</List.Item>
                    </DatePicker>
                  </div>
                </div>
              </div>
            }
          </div>
        </div>
        <div style={{borderTop:'10px solid #F3F3F5'}}></div>
        <div style={{ margin: "12px 26px",width:'86%',height:'64px',border:'1px solid #EDEEF2' }} className="text">
          <InputItem
            labelNumber={8}
            clear
            onChange={(e) => {
              this.setState({
                leaveMessage: e
              })
            }}
            placeholder={T("Scrivi qui la tua nota per il venditore(备注)")}
          ></InputItem>
        </div>
        <div style={{padding:'0 16px 0px'}}>
          {this.renderList()}

        </div>
        <div style={{color: "#9C9BAB",fontWeight:'bold',fontSize:'12px',marginBottom:'87px'}}>
          <div data-flex="cross:center box:first" style={{ padding: "10px", paddingLeft: "25px", height: "44px", }}>
            <div style={{ marginRight: "10px", }}>
              {T("Subtotal(商品金额)")}：
            </div>
            <div style={{  textAlign: "right", }}>
              € {totalPrice.toFixed(2)}
            </div>
          </div>
          <div data-flex="cross:center box:first" style={{ padding: "10px", paddingLeft: "25px", height: "44px" }}>
            <div style={{ marginRight: "10px" }}>
              {T("Shipping(物流运费)")}：
            </div>
            <div style={{textAlign: "right",}}>+€

              {
                order_type == 0 ? delivery_price.toFixed(2): "0.00"
              }

            </div>
          </div>
          <div data-flex="cross:center box:first" style={{ padding: "10px", paddingLeft: "25px", height: "44px", }}>
            <div style={{ marginRight: "10px",color:'#595867' }}>
              {T("Totale(合计)")}：
            </div>
            <div style={{  textAlign: "right",color:'#F09600',fontSize:'20px' }}>
              € {total.toFixed(2)}
            </div>
          </div>
        </div>
        {
          cartItems.length > 0 &&
          <div style={{position: "fixed", bottom: 0, width: "100%", borderTop: "1px solid #ddd", background: "#fff", padding: "0 10px" }}>
            <div style={{ fontSize: "13px",color:'#2E2D35',fontWeight:'bold',width:'50%',margin:'16px auto',textAlign:'center' }}>
              {T("Total(合计)")}: <span style={{ color: "#F09600",fontSize:'20px' }}>€
              {total.toFixed(2)}
              </span>
            </div>
            <Button  type="primary" size="default" style={{ margin: "0 auto 20px",width:'80%',background:'#F09600',borderRadius:'15px',border:'0px' }} onClick={() => {this.confirmOrder() }} disabled={isOn}>{T("Conferma(提交)")}</Button>
          </div>
        }
      </div >
    )
  }
}
